package jdbclianxi20250325;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCDemo1 {
    public static void main(String[] args) {
        /*
        使用JDBC链接数据库的大致流程:
        1.加载驱动
        2.使用DriverManager(JDBC提供的)再通过加载的驱动与数据库建立连接:Connection对象
        3.通过连接对象创建语句对象Statement
        4.通过语句对象执行SQL语句
        5.如果执行的是查询语句还会得到结果集ResultSet,对其进行遍历获取查询结果
        6.关闭数据库的连接


        */

        try {
            //1加载驱动(Mysql驱动)
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2与数据库进行连接
            Connection connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/mysql?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true",
                        "root",
                        "root");
            System.out.println("连接数据库成功");

            //通过连接对象创建语句对象Statement
            Statement statement = connection.createStatement();

            String sql = "CREATE TABLE shitou( " +
                    "    id INT PRIMARY KEY AUTO_INCREMENT, " +
                    "    username VARCHAR(32), " +
                    "    password VARCHAR(32), " +
                    "    nickname VARCHAR(32), " +
                    "    age INT(3) " +
                    ")";
            // 4.通过语句对象执行SQL语句
         statement.execute(sql);
            System.out.println("创建完毕");
            //6.关闭数据库的连接
            connection.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
